﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MapTeams.Umbraco.Polls.Dto;
using MapTeams.Umbraco.Polls.Services;

namespace MapTeams.Umbraco.Polls.UI.Controls
{
    public partial class PollWidget : System.Web.UI.UserControl
    {
        public string PollId { get; set; }
        private string _cssFileLocation = null;
        public string CssFileLocation
        {
            get
            {
                if (string.IsNullOrEmpty(_cssFileLocation))
                    return PollsConfig.DefaultCssPath;
                
                return _cssFileLocation;
            }
            set { _cssFileLocation = value; }
        }

        /// <summary>
        /// will only read pollId from queryString if PollId property has been set to "TESTINGONlY"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                divMsg.Visible = false;

                if (!IsPostBack)
                {
                    string errorMessage = IsValid();
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        divMsg.Visible = true;
                        divMsg.InnerHtml = string.Format("<b>Error validating: </b> {0} ", errorMessage);

                        return;
                    }

                    if (!String.IsNullOrEmpty(PollId)
                        &&PollId.ToUpper()!="TESTINGONLY") 
                    {
                        hidPollID.Value = PollId;
                    }
                    else //show a random Active Poll or PollId from queryString if there is one
                    {
                        //saving the poll id in a hidden variable to use later
                        PollsServiceLayer objPoll = new PollsServiceLayer();
                        int pollID;
                        string pollIdPar = Request.QueryString[Constants.PollIdPar];

                        if (string.IsNullOrEmpty(pollIdPar))
                            pollID = objPoll.getRandomActivePollID();
                        else 
                            pollID = int.Parse(pollIdPar);

                        if (pollID > 0)
                            hidPollID.Value = pollID.ToString();
                        else
                        {
                            divMsg.InnerHtml = "<b>Note: </b>There are no active polls available.";
                            divMsg.Visible = true;
                            return;
                        }
                    }
                    
                    ShowPoll();
                }
            }
            catch(Exception ex)
            {
                divMsg.Visible = true;
                divMsg.InnerHtml = ex.Message;
            }
        }

        private string IsValid()
        {
            string errorMessage = string.Empty;
            if (string.IsNullOrEmpty(PollId))
                errorMessage += "PollId has not been set" ;

            return errorMessage;
        }

        private void ShowPoll()
        {
            PollsServiceLayer objPoll = new PollsServiceLayer(); //todo: use factory design pattern later //inject dependency from webConfig
            int pollId = int.Parse(hidPollID.Value);
            DataSet dsPoll = objPoll.SelectPoll(pollId);

            bool isPollFound = dsPoll.Tables[0].Rows.Count > 0;

            if (!isPollFound)
            {
                divMsg.InnerHtml = "<b>Note: </b>The poll you are looking for is not found.";
                divMsg.Visible = true;
                return;
            }

            MapTeamsPolls pollInfo = PollsUtils.BuildPoll(dsPoll);

            //if the BlockMode is not NONE findout whether the user is already Polled or not - if polled show the result only
            string blockMode = pollInfo.BlockMode;

            bool isPolled = CheckAlreadyPolled(blockMode);
            pollInfo.IsAlreadyVoted = isPolled;

            //will either show input form or bar graph 
            //depend on IsAlreadyVoted flag
            string template = GetMustacheTemplate();
            MapTeamsPollsContainer.InnerHtml += PollsUtils.ShowPoll(template, pollInfo);
        }

        public string GetMustacheTemplate()
        {
            LiteralControl objPanelText = MustacheTemplate.Controls[0] as LiteralControl;
            return objPanelText.Text;
        }

        /// <summary>
        /// I do not want to refactor this one yet
        /// as long as the functionality is correct.
        /// </summary>
        /// <param name="blockMode"></param>
        /// <returns></returns>
        private bool CheckAlreadyPolled(string blockMode)
        {
            bool isPolled = false;
            //if the block mode of this Poll is by IP,, check in the DB whether a poll is already existing from this IP
            if (blockMode == PollsServiceLayer.BlockMode.IP_ADDRESS.ToString())
            {
                string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                PollsServiceLayer objPoll = new PollsServiceLayer();
                int id = objPoll.SelectPollIP(int.Parse(hidPollID.Value), ip);
                if (id > 0) isPolled = true;
            }
            else if (blockMode == PollsServiceLayer.BlockMode.COOKIE.ToString()) //If block by Cookie read the cookie to see if there is an entry for this blog
            {
                if (Request.Cookies[Constants.CookieName] != null && Request.Cookies[Constants.CookieName]["ID"] != null)
                {
                    //the cookie will have comma seperated IDs of all the polls that already voted
                    string commaSeperatedPollIDs = Request.Cookies[Constants.CookieName]["ID"];
                    //split it with comma
                    string[] pollIDs = commaSeperatedPollIDs.Split(",".ToCharArray());
                    //and loop through each pollID to find whethere the current poll is already voted
                    foreach (string pID in pollIDs)
                    {
                        //if yes break
                        if (pID == hidPollID.Value)
                        {
                            isPolled = true;
                            break;
                        }
                    }
                }
            }

            return isPolled;
        }

    }
}
